package com.my.test.thread.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class BankWaterService implements Runnable {


    // 创建4个屏障，处理完之后执行当前run方法
    private CyclicBarrier c = new CyclicBarrier(4, this);

    // 假设有4个sheet，所以启动4个线程
    private Executor executor = Executors.newFixedThreadPool(4);

    // 保存每个sheet计算出来的银行流水结果
    @SuppressWarnings({"unchecked", "rawtypes"})
    private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap();


    synchronized private void count() {
        for (int i = 0; i < 4; i++) {
            executor.execute(new Thread(() -> {
                // https://blog.csdn.net/cdw8131197/article/details/52434908
                sheetBankWaterCount.put(Thread.currentThread().getName(), 2);

                // 插入一个屏障
                try {
                    c.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }));

			/*executor.execute(new Runnable() {
				@Override
				public void run () {
					sheetBankWaterCount.put(Thread.currentThread().getName(), 1);
					try {
						c.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});*/
        }
    }

    @Override
    synchronized public void run() {
        int result = 0;
        // 汇总每个sheet计算出的结果
        /*for (Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
            result = result + sheet.getValue();
        }*/
        for (int value :sheetBankWaterCount.values()) {
            result = result + value;
        }
        // 输出结果
        sheetBankWaterCount.put("result", result);
        System.out.println(result);

    }

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.count();
    }


}
